package org.phantom.securityframework.datapermission.internal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.phantom.securityframework.api.Account;
import org.phantom.securityframework.api.AccountManager;
import org.phantom.securityframework.api.GroupManager;
import org.phantom.securityframework.api.datapermission.DataDimension;
import org.phantom.securityframework.api.datapermission.DimensionType;
import org.phantom.securityframework.api.domain.Group;
import org.phantom.securityframework.auth.realm.SubjectDataPermissionRealm;
import org.phantom.securityframework.datapermission.DimensionQuery;
import org.phantom.securityframework.datapermission.DimensionQueryCreator;
import org.phantom.securityframework.datapermission.QueryParameters;
import org.springframework.stereotype.Service;

/**
 * 过滤条件生成器默认实现
 * 1.先获取当前用户,根据用户所在组明确可查询的维度
 * 2.查询每个维度下的过滤值
 * @author apple
 *
 */
@Service("dimensionQueryCreatorDefaultImpl")
public class DimensionQueryCreatorDefaultImpl implements DimensionQueryCreator{


	@Resource
	protected AccountManager accountManager = null;
	@Resource
	protected GroupManager groupManager = null;
	@Resource
	protected SubjectDataPermissionRealm dataPermissionRealm = null;
	
	@Override
	public DimensionQuery createQuery(Object[] args) {
		String accountId=SecurityUtils.getSubject().getPrincipal().toString();
		Map<String, List<DimensionType>> dimensionMappedValue = new HashMap<String, List<DimensionType>>();
        
        Account account = accountManager.get(accountId);
        List<Group> groups = account.getGroups();
        List<DataDimension> groupDimensions = new ArrayList<DataDimension>();
        for (Group group : groups) {
        	groupDimensions.add(groupManager.getDataDimension(group));
		}
        for (DataDimension d : groupDimensions) {
        	for (DimensionType t : d.getDimensionType()) {
        		List<DimensionType> types = dataPermissionRealm.getSubjectDataDimensins(accountId, t.getDimensionDesc());
        		dimensionMappedValue.put(t.getDimensionDesc(),types);
			}
		}
        QueryParameters parameters = this.resolveQueryParameters(args);
        DimensionQuery query = new DimensionQueryDefaultImpl(parameters,dimensionMappedValue);
        return query;
	}


	protected QueryParameters resolveQueryParameters(Object[] args){
		for (Object object : args) {
			if(object instanceof QueryParameters)
				return (QueryParameters) object;
		}
		return null;
	}

}
